<?php

error_reporting(E_ALL);

$con = array(
	'root_path'=>$_SERVER['DOCUMENT_ROOT'],
	'admin'=>'mogu',
	'pwd'=>'123456',
);

// 加密密钥
$key = 'weoinfdjnj';

// 登录验证
if(isset($_POST['admin'])){
	if($_POST['admin'] == $con['admin'] && $_POST['pwd'] == $con['pwd']){
		setcookie('mogu',md5($con['admin'].$key));
	}else{
		login_html();
		exit();
	}
}else{
	// 检查Cookie
	if(!isset($_COOKIE['mogu'])){
		login_html();
		exit();
	}else{
		if($_COOKIE['mogu'] != md5($con['admin'].$key)){
			login_html();
			exit();
		}
	}
}

if(isset($_POST['dir'])){
	// 文件列表
	$path = $_POST['dir'] == '/' ? $con['root_path'] : $con['root_path'].$_POST['dir'] ;
	if ($handle = opendir($path)) {
		$dir = array();
		$files = array();
		while (false !== ($file = readdir($handle))) {
			if(!in_array($file,array('.','..'))){
				if(is_dir($path.'/'.$file)){
					$dir_path = $path.'/'.$file;
					$dir[] = array(
						'name'=>$file,
						'ctime'=>date("Y-m-d H:i:s",filectime($dir_path)),
						'mtime'=>date("Y-m-d H:i:s",filemtime($dir_path)),
						'perm'=>substr(sprintf("%o",fileperms($dir_path)),-4),
						'path'=>$_POST['dir'].$file,
					);
				}else{
					$file_path = $path.'/'.$file;
					$files[] = array(
						'name'=>$file,
						'ctime'=>date("Y-m-d H:i:s",filectime($file_path)),
						'mtime'=>date("Y-m-d H:i:s",filemtime($file_path)),
						'fsize'=>fsize(filesize($file_path)),
						'perm'=>substr(sprintf("%o",fileperms($file_path)),-4),
					);
				}
			}
		}
		closedir($handle);
		$result = array(
			'dir'=>$dir,
			'file'=>$files,
			'path'=>explode('/', $_POST['dir']),
		);
		echo json_encode($result);
	}else{
		echo 0;
	}
}elseif(isset($_POST['copy'])){
	// 复制
	foreach($_POST['file'] as $f){
		$file = $con['root_path'].$f;
		$copyto = $con['root_path'].$_POST['copyto'].'/'.basename($f);
		if(is_dir($file)){
			Copydir($file,$copyto);
		}else{
			if(copy($file,$copyto)){
				echo 1;
			}
		}
	}
}elseif(isset($_POST['move'])){
	// 移动
	$n = 0;
	foreach($_POST['file'] as $f){
		$file = $con['root_path'].$f;
		$moveto = $con['root_path'].$_POST['moveto'].'/'.basename($f);
		if(rename($file,$moveto)){
			$n += 1;
		}
	}
	if($n == count($_POST['file'])){
		echo 1;
	}
}elseif(isset($_POST['del'])){
	// 删除
	$n = 0;
	foreach($_POST['file'] as $f){
		$path = $con['root_path'].$f;
		if(is_dir($path)){
			if(deldir($path)){
				$n += 1;
			}
		}else{
			if(unlink($path)){
				$n += 1;
			}
		}
	}
	if($n == count($_POST['file'])){
		echo 1;
	}
}elseif(isset($_POST['rename'])){
	// 重命名
	$path = $con['root_path'].$_POST['file'];
	if(rename($path,dirname($path).'/'.$_POST['rename'])){
		echo 1;
	}
}elseif(isset($_POST['make'])){
	// 新建文件
	if($_POST['type'] == 'file'){
		if(fopen($con['root_path'].$_POST['file'],'w')){
			echo 1;
		}
	}else{
		if(mkdir($con['root_path'].$_POST['file'])){
			echo 1;
		}
	}
}elseif(isset($_GET['down'])){
	// 下载
	header("Content-Type: application/force-download");
    header("Content-Disposition: attachment; filename=".basename($_GET['file']));
    readfile($con['root_path'].$_GET['file']);
}elseif(isset($_POST['perm'])){
	// 改变文件权限
	if(chmod($con['root_path'].$_POST['file'], octdec($_POST['perm']))){
		echo 1;
	}else{
		echo 0;
	}
}elseif(isset($_POST['zip'])){
	// 压缩
	if(zip($con['root_path'].$_POST['file'],$_POST['name'])){
		echo 1;
	}
}elseif(isset($_POST['unzip'])){
	// 解压
	foreach($_POST['files'] as $v){
		unzip($con['root_path'].$v);
	}
}elseif(isset($_FILES['file'])){
	// 批量上传
    $i = 0;
    while(isset($_FILES['file']['tmp_name'][$i])){
        move_uploaded_file($_FILES['file']['tmp_name'][$i], $con['root_path'].$_POST['up_path'].$_FILES['file']['name'][$i]);
        $i++;
    }
    exit('<script type="text/javascript">alert("上传成功")</script>');
}elseif(isset($_POST['curl'])){
	// 离线下载
	$url = $_POST['url'];
	$ch = curl_init($url);
	$dir = $con['root_path'].$_POST['path'];
	$urlname = $dir.basename($url);
	$fp = fopen($urlname, "wb");
	curl_setopt($ch, CURLOPT_FILE, $fp);
	$ok = curl_exec($ch);
	curl_close($ch);
	fclose($fp);
}elseif(isset($_POST['filesize'])){
	// 获取远程文件大小
	$file_info = array(
		'path'=>$_POST['path'].basename($_POST['url']),
		'size'=>get_url_filesize($_POST['url']),
	);
	echo json_encode($file_info);
}elseif(isset($_POST['fsize'])){
	// 获取本地文件大小
	echo filesize($con['root_path'].$_POST['file']);
}elseif(isset($_POST['config'])){
	// 头部信息
	$config = array(
		'host'=>$_SERVER['SERVER_NAME'].'('.gethostbyname($_SERVER['SERVER_NAME']).')',
		'ip'=>$_SERVER['REMOTE_ADDR'],
	);
	echo json_encode($config);
}elseif(isset($_POST['exit'])){
	setcookie('mogu', null);
	echo 1;
}else{
	index();
}

########   函数   ########

// 文件大小
function fsize($s) {
	foreach (array('','K','M','G') as $i => $k) {
		if ($s < 1024) break;
		$s/=1024;
	}
	$data = round($s,2).$k."B";
	return $data;
}

// 删除目录
function deldir($dir){
	$dh = opendir($dir);
	while($file = readdir($dh)){
		if($file!='.' && $file!='..'){
			$path = $dir.'/'.$file;
			if(is_dir($path)){
				deldir($path);
			}else{
				unlink($path);
			}
		}
	}
	closedir($dh);
	if(rmdir($dir)){
		return true;
	}else{
		return false;
	}
}

// 解压缩文件
function unzip($file){
    $zip = new ZipArchive;
    if ($zip->open($file) === TRUE) {
        $zip->extractTo(dirname($file));
        $zip->close();
        return true;
    } else {
        return false;
    }
}

// 压缩文件或目录
function zip($file,$name){
    $zip = new ZipArchive;
    if($zip->open(dirname($file).'/'.$name,ZIPARCHIVE::CREATE) === false){
        return false;
    }
    if(is_dir($file)) {
        $zip->addEmptyDir(basename($file));
        $dh = opendir($file);
        while($f = readdir($dh)) {
            if($f!='.' && $f!='..'){
                $path = $file.'/'.$f;
                if(is_dir($path)) {
                    $zip->addEmptyDir(basename($file).'/'.$f);
                }else{
                    $zip->addFile($path,basename($file).'/'.$f);
                }
            }
        }
        closedir($dh);
    }else{
        $zip->addFile($file,basename($file));
    }
    $zip->close();
    return true;
}

// 复制文件夹
function Copydir($from,$to){
    if(is_dir($from)) {
        if(!file_exists($to)) {
            mkdir($to);
        }
        $files = scandir($from);
        foreach($files as $file){
            if($file!="."&&$file!=".."){
				Copydir($from.'/'.$file,$to.'/'.$file);
            }
        }
    }else{
		copy($from,$to);
    }
}

// 获取远程文件大小
function get_url_filesize($url,$user='',$pw=''){
	ob_start();
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_HEADER, 1);
	curl_setopt($ch, CURLOPT_NOBODY, 1);
	if (!empty($user)&&!empty($pw)) {
		$headers = array('Authorization: Basic ' . base64_encode($user.':'.$pw));
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	}
	$okay = curl_exec($ch);
	curl_close($ch);
	$head = ob_get_contents();
	ob_end_clean();
	$regex = '/Content-Length:\s([0-9].+?)\s/';
	$count = preg_match($regex, $head, $matches);
	if (isset($matches[1])) {
		$size = $matches[1];
	} else {
		$size = 'unknown';
	}
	return $size;
}

// 主页
function index(){
	echo <<<EOK
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8"/>
		<title>蘑菇 - PHP文件管理器</title>
		<meta name="keywords" content="mogu php file manager"/>
		<meta name="description" content=" a filemanager for php by mogublog"/>
		<link rel="stylesheet" href="css/style.css"/>
		<script type="text/javascript" src="js/jquery-1.7.2.min.js" id="load_jquery" onerror="Load(0)"></script>
		<script type="text/javascript" src="js/mogu.js"></script>
	</head>
	<body>
		<div class="main_info">
			<div class="result"></div>
		</div>
		<div class="main">
			<div class="head">
				<table class="m-table m-table-rds root">
					<thead>
						<tr><th><a href="" >蘑菇 - PHP文件管理器</a></th></tr>
					</thead>
				</table>
				<table class="m-table m-table-rds">
					<thead>
						<tr><th id="host">主机：</th><th id="time">时间：</th><th id="ip">IP：</th><th id="exit"><a href="javascript:void(0);">退出</a></th></tr>
					</thead>
					<tbody class="info">
						<tr>
							<td class="path">路径：<a href="javascript:void(0);" class="goroot" >root</a><span id="path"></span></td>
							<td colspan="2">离线下载：<input type="text" class="u-ipt url" value="" /><button type="button" class="u-btn u-btn-c4 curl">下载</button></td>
							<td id="upgrade"><a href="javascript:void(0);">升级</a></td>
						</tr>
					</tbody>
				</table>
			</div>
			<div class="body">
				<table class="m-table m-table-rds">
					<thead>
						<tr><th class="cola">文件名</th><th class="colb">创建日期</th><th class="colb">修改日期</th><th class="colc">大小</th><th class="colc">属性</th><th>操作</th></tr>
						<tr>
							<td colspan="6" class="left">
								<a href="javascript:void(0);" id="back">返回</a>
								<div class="u-progress go">
									<span class="pgbar" style="width:0%;"><span class="pging" ></span></span>
								</div>
							</td>
						</tr>
					</thead>
					<tbody class="list">
					</tbody>
					<tfoot class="footer">
						<tr>
							<td colspan="6" class="left">
								<input type="checkbox" class="all">选中文件：
								<button type="button" class="u-btn u-btn-c4 copys">复制</button>
								<button type="button" class="u-btn u-btn-c4 moves">移动</button>
								<button type="button" class="u-btn u-btn-c4 dels">删除</button>
								<button type="button" class="u-btn u-btn-c4 zips">压缩</button>
								<button type="button" class="u-btn u-btn-c4 unzip">解压</button>
							</td>
						</tr>
					</tfoot>
				</table>
			</div>
			<div class="foot">
				<table class="m-table m-table-rds">
					<tr>
						<td>
							<form action="" method="post" class="upload_form" enctype="multipart/form-data" target="hidden_frame">
								<div class="u-upload">批量上传：
								<button type="button">选择文件</button>
								<input type="file" name="file[]" class="upload" multiple />
								</div>
								<input type="hidden" class="up_path" name="up_path" value="" />
								<input type="submit" class="u-btn u-btn-c4" value="上传" />
							</form>
							<iframe name='hidden_frame' id="hidden_frame" style='display:none'></iframe>
						</td>
						<td>新建：<input type="text" class="u-ipt new" value="" /><button type="button" class="u-btn u-btn-c4 newfile">文件</button><button type="button" class="u-btn u-btn-c4 newdir">目录</button></td>
					</tr>
				</table>
			</div>
		</div>
	</body>
</html>
EOK;
}

// 登录页面
function login_html(){
	echo <<<EOK
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8"/>
		<title>蘑菇 - PHP文件管理器</title>
		<meta name="keywords" content="mogu php file manager"/>
		<meta name="description" content=" a filemanager for php by mogublog"/>
		<link rel="stylesheet" href="style.css"/>
		<script type="text/javascript">
			function login(){
				var form = document.getElementById('login_form');
				form.submit();
			}
		</script>
	</head>
	<body>
		<div class="login">
			<div class="m-form">
				<form action="" id="login_form" method="post">
					<fieldset>
						<div class="formitm">
							<label class="lab">用户名：</label>
							<div class="ipt">
								<input type="text" class="u-ipt" name="admin" />
							</div>
						</div>
						<div class="formitm">
							<label class="lab">密码：</label>
							<div class="ipt">
								<input type="password" class="u-ipt" name="pwd" />
							</div>
						</div>
						<div class="formitm formitm-1">
							<button class="u-btn" type="button" onclick="login()"> 登录 </button>
						</div>
					</fieldset>
				</form>
			</div>
		</div>
	</body>
</html>
EOK;
}
